#include "stm32f0xx_conf.h"
#include "delay.h"

void hw_delay_init()
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

    TIM_DeInit(TIM1);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);

    TIM_TimeBaseStructure.TIM_Period = 0;
    TIM_TimeBaseStructure.TIM_Prescaler = 24;
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 1;
    TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

    TIM_ITConfig(TIM1, TIM_IT_Update, DISABLE);

    TIM_Cmd(TIM1, DISABLE);
}

void hw_delay_us(uint32_t nus)
{
    TIM_SetAutoreload(TIM1, nus - 3);
    TIM_SetCounter(TIM1, 0);
    TIM_Cmd(TIM1, ENABLE);
    TIM_ClearFlag(TIM1, TIM_FLAG_Update);
    while (TIM_GetFlagStatus(TIM1, TIM_FLAG_Update) == RESET)
    {
        ;
    }
    TIM_Cmd(TIM1, DISABLE);
}

void hw_delay_ms(uint16_t nms)
{
    while (nms-- > 0)
    {
        hw_delay_us(1000);
    }
}

void hw_delay_loop(uint32_t nus)
{
    volatile uint32_t m = 0;

    while (m++ < nus)
    {
        ;
    }
}

